package com.qskj.springsecurity.single.service;

import com.qskj.springsecurity.single.mapper.UserMapper;
import com.qskj.springsecurity.single.pojos.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author shikf
 * @version 1.0     2021-02-03 16:38
 */
@Service
//@Primary
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User byUsername = userMapper.findByUsername(username);
        if (byUsername == null ) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 将数据形式的roles解析为UserDetails的权限集
        //AuthorityUtils.commaSeparatedStringToAuthorityList()是springsecurity提供的将权限集字符串切割可用权限对象列表
        byUsername.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(byUsername.getRoles()));
        return byUsername;
    }
}
